// pages/utils/wikiapi.js
export const buildStructuredTreeData = (treeData, listData) => {
  // 1. 创建节点映射表
  const nodeMap = new Map();
  
  // 2. 处理所有路径（包括中间路径）
  const processPath = (item, isExplicitFolder = false) => {
    const rawPath = item.path;
    const isFolder = isExplicitFolder || (treeData.includes(item) && item.isFolder) || rawPath.endsWith('/');
    const cleanPath = isFolder ? rawPath.replace(/\/$/, '') : rawPath;
    const pathParts = cleanPath.split('/');
  
    // 确保所有父路径都存在
    let currentPath = '';
    pathParts.forEach((part, index) => {
      currentPath = currentPath ? `${currentPath}/${part}` : part;
      const isLeaf = index === pathParts.length - 1 && !isFolder;
  
      if (!nodeMap.has(currentPath)) {
        nodeMap.set(currentPath, {
          id: isLeaf ? item.id : `folder-${currentPath}`,
          title: part,
          path: currentPath,
          isFolder: !isLeaf,
          children: [],
          depth: index,
          isVirtual: true,
          data: null
        });
      }
  
      // 更新当前节点信息
      const currentNode = nodeMap.get(currentPath);
      if (isLeaf || isExplicitFolder) {
        Object.assign(currentNode, {
          isVirtual: false,
          data: item,
          id: item.id,
          isFolder: isExplicitFolder || currentNode.isFolder
        });
      }
    });
  };
  
  // 3. 处理tree数据（明确指定的文件夹）
  treeData.forEach(item => processPath(item, true));
  
  // 4. 处理list数据
  listData.forEach(item => processPath(item));
  
  // 5. 构建层级关系
  const rootNodes = [];
  nodeMap.forEach((node, path) => {
    if (node.depth === 0) {
      rootNodes.push(node);
    } else {
      const parentPath = path.split('/').slice(0, -1).join('/');
      if (nodeMap.has(parentPath)) {
        const parent = nodeMap.get(parentPath);
        if (!parent.children.some(child => child.path === path)) {
          parent.children.push(node);
        }
      }
    }
  });
  
  // 6. 特殊处理：既是文件夹又是叶节点的项
  nodeMap.forEach(node => {
    if (node.data && node.children.length > 0) {
      // 创建文件夹副本
      const folderNode = {
        ...node,
        id: `folder-${node.path}`,
        isFolder: true,
        data: null,
        isVirtual: false
      };
      
      // 找到父节点并插入
      const parentPath = node.path.split('/').slice(0, -1).join('/');
      if (nodeMap.has(parentPath)) {
        const parent = nodeMap.get(parentPath);
        const index = parent.children.findIndex(n => n.path === node.path);
        if (index >= 0) {
          parent.children.splice(index, 0, folderNode);
        }
      }
    }
  });
  
  // 7. 排序
  const sortChildren = (nodes) => {
    nodes.forEach(node => {
      if (node.children.length > 0) {
        node.children.sort((a, b) => {
          if (a.isFolder !== b.isFolder) return a.isFolder ? -1 : 1;
          return a.title.localeCompare(b.title);
        });
        sortChildren(node.children);
      }
    });
  };
  sortChildren(rootNodes);
  
  return rootNodes;
};

export const findItemByPath = (treeData, path) => {
  const find = (nodes) => {
    for (const node of nodes) {
      if (node.path === path) return node;
      if (node.children) {
        const found = find(node.children);
        if (found) return found;
      }
    }
    return null;
  };
  return find(treeData);
};